<template>
  <div>
    <van-nav-bar
      title="注册"
      left-text="返回"
      right-text="..."
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="register">
      <van-form @submit="register">
        <van-field
          v-model="formData.phone"
          name="用户名"
          placeholder="用户名"
          :rules="[
            {
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请填写用户名',
            },
          ]"
        />
        <van-field
          v-model="formData.pass"
          type="password"
          name="密码"
          placeholder="密码"
          :rules="[
            { required: true, pattern: /^\d{4}$/, message: '请填写密码' },
          ]"
        />
        <van-field
          v-model="formData.checkpass"
          type="password"
          name="确认密码"
          placeholder="确认密码"
          :rules="[{ required: true, pattern: /^\d{4}$/, message: '确认密码' }]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >注册</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { user_register } from "../utils/api";
export default {
  data() {
    return {
      formData: {
        phone: "",
        pass: "",
        checkpass: "",
      },
    };
  },
  methods: {
    register() {
      if (this.formData.pass !== this.formData.checkpass) {
        alert("密码和确认密码不一致");
      } else {
        //验证通过
        // 深拷贝formData
        var newFormData = JSON.parse(JSON.stringify(this.formData));
        // 删除对象的checkpass属性
        delete newFormData.checkpass;

        // 发起注册请求
        user_register(newFormData).then((res) => {
          if (res.data.code == 200) {
            alert("注册成功");
            this.$router.push("/login");
          } else {
            alert(res.data.msg);
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.register {
  margin: 50% 20px;
}
.van-field {
  border: 1px solid gainsboro;
  border-radius: 20px;
  margin: 20px 0;
}
.register .title {
  font-weight: bold;
  text-align: center;
  line-height: 40px;
}
.register .block {
  margin: 20px 0;
}
.register .block input {
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 20px;
  padding-left: 20px;
  box-sizing: border-box;
  outline: none;
  width: 100%;
}
</style>
